<script setup lang="ts">
import { request } from '@/apis'
import b64toBlob from 'b64-to-blob'
import { showLoadingToast, showToast, type ActionSheetAction } from 'vant'
import { onMounted, ref } from 'vue'
const showAvatarSheet = ref(false)
const actions = [{ name: '拍照' }, { name: '相册' }]
const onCancel = () => showToast('取消')
const onSelect = async (action: ActionSheetAction, index: number) => {
  if (index === 0) {
    const res = await mk.pickerCamera()
    console.log('拍照', res)
  } else if (index === 1) {
    const res = await mk.pickerPhoto()
    console.log('相册', res)
    onUpdateAvatar(res)
  }
}

// 1.3 头像上传
const onUpdateAvatar = async (data: string) => {
  try {
    showAvatarSheet.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    const image = b64toBlob(data, 'image/jpeg')
    const fd = new FormData()
    fd.append('file', image, Date.now() + '.jpeg')
    const res = await request.post<MkResponse<{ avatar: string }>>('member/profile/avatar', fd)
    profile.value.avatar = URL.createObjectURL(image)
    const user = mk.queryUser()
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    showToast({ message: '上传成功' })
  } catch (err) {
    showToast({ message: '上传失败' })
  }
}
//生日
const showBirthdayPop = ref(false)
const currentDate = ref(['2021', '01', '01'])
const minDate = new Date(2020, 1, 1)
const maxDate = new Date(2030, 12, 31)
const onBirthdayConfirm = () => {
  console.log(currentDate.value)
  profile.value.birthday = currentDate.value.join('-')
  showBirthdayPop.value = false
}
//地区
const showAreaPop = ref(false)

const areaList = ref<AreaColumns>({} as AreaColumns)
onMounted(async () => {
  areaList.value = await mk.getAreaColumns()
  // console.log(areaList.value)
})
const onAreaConfirm = ({ selectedValues, selectedOptions, selectedIndexes }) => {
  // console.log(selectedOptions)
  profile.value.provinceCode = selectedValues[0]
  profile.value.cityCode = selectedValues[1]
  profile.value.countyCode = selectedValues[2]
  const arr = selectedOptions.map((v) => {
    return v.text
  })
  // console.log(arr)
  profile.value.fullLocation = arr.join(' ')
  showAreaPop.value = false
}
// 职业弹层
const showJobPop = ref(false)
const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' },
  { text: '0', value: '0' },
]
const selectJob = ref<string[]>([])
const onConfirm = () => {
  // showToast(`当前值: ${selectedValues.join(',')}`)
  // showToast(`当前值: ${selectJob.value.join(',')}`)
  profile.value.profession = selectJob.value[0]
  showJobPop.value = false
}
//回显
const profile = ref({} as ProfileInfo)
onMounted(async () => {
  const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
  // console.log(res.data.result)
  profile.value = res.data.result
  // console.log(profile.value)
  currentDate.value = profile.value.birthday.split('-')
  selectJob.value = [profile.value.profession]
})

//提交数据
const onSumbitData = async () => {
  // console.log(profile.value)
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
  })
  const res = await request.put<MkResponse<ProfileInfo>>('/member/profile', profile.value)
  // console.log(res)
  mk.updateUser(res.data.result)
  showToast('修改成功')
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        round
        width="100"
        height="100"
        class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true"
      >
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
        <van-action-sheet
          v-model:show="showAvatarSheet"
          :actions="actions"
          cancel-text="取消"
          close-on-click-action
          @cancel="onCancel"
          @select="onSelect"
        />
      </div>
    </div>

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field v-model="profile.id" label="账号" readonly></van-field>
      <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field
        @click="showBirthdayPop = true"
        label="生日"
        readonly
        v-model="profile.birthday"
        placeholder="请选择日期"
      ></van-field>

      <van-popup v-model:show="showBirthdayPop" position="bottom">
        <van-date-picker
          v-model="currentDate"
          title="选择日期"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onBirthdayConfirm"
          @cancel="showBirthdayPop = false"
        />
      </van-popup>
      <!-- ---------------------------------------------所在地弹层-------------------------------------------------------------------- -->
      <van-popup v-model:show="showAreaPop" position="bottom">
        <van-area
          title="标题"
          :area-list="areaList"
          @confirm="onAreaConfirm"
          @cancel="showAreaPop = false"
        />
      </van-popup>
      <!-- ---------------------------------------------所在地弹层-------------------------------------------------------------------- -->

      <van-field
        @click="showAreaPop = true"
        label="所在地"
        readonly
        v-model="profile.fullLocation"
        placeholder="请选择所在地"
      ></van-field>

      <van-field
        @click="showJobPop = true"
        label="职业"
        readonly
        v-model="profile.profession"
        placeholder="请选择职业"
      ></van-field>
    </van-cell-group>
    <!-- ---------------------------------------------职业弹层-------------------------------------------------------------------- -->
    <van-popup v-model:show="showJobPop" position="bottom">
      <van-picker
        v-model="selectJob"
        @confirm="onConfirm"
        @cancel="showJobPop = false"
        :columns="columns"
      />
    </van-popup>

    <!-- ---------------------------------------------职业弹层-------------------------------------------------------------------- -->
    <div class="submit">
      <van-button @click="onSumbitData" round block type="primary"> 保存资料 </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
